package main

import (
	"flag"
	"git.oschina.net/dddailing/annotate/server"
	"github.com/dailing/levlog"
	"github.com/go-xorm/xorm"
	"os"
	"strings"
)

func mapToList(m map[string]string, order []string) []string {
	t := make([]string, 0)
	for _, key := range order {
		t = append(t, m[key])
	}
	return t
}

func ExportAnnotationFromDB(outputFileName string) {
	engine, err := xorm.NewEngine("mysql", "root:123456@tcp(mysql)/"+server.DB_NAME)
	levlog.E(err)
	queryResult, err := engine.QueryString("select * from image_annotation left join image on image.id = image_annotation.image")
	keys := make([]string, 0, 0)
	for key := range queryResult[0] {
		keys = append(keys, key)
	}
	of, err := os.Create(outputFileName)
	defer of.Close()
	levlog.E(err)
	levlog.Info(keys)
	_, err = of.Write([]byte(strings.Join(keys, ",") + "\n"))
	levlog.E(err)
	for _, row := range queryResult {
		strLine := strings.Join(mapToList(row, keys), ",") + "\n"
		_, err = of.Write([]byte(strLine))
		levlog.E(err)
		//break
	}
}

func ExportImageDB(outputFileName string) {
	engine, err := xorm.NewEngine("mysql", "root:123456@tcp(mysql)/"+server.DB_NAME)
	levlog.E(err)
	queryResult, err := engine.QueryString("select path, grade as level from image")
	keys := make([]string, 0, 0)
	for key := range queryResult[0] {
		keys = append(keys, key)
	}
	of, err := os.Create(outputFileName)
	defer of.Close()
	levlog.E(err)
	levlog.Info(keys)
	_, err = of.Write([]byte(strings.Join(keys, ",") + "\n"))
	levlog.E(err)
	for _, row := range queryResult {
		strLine := strings.Join(mapToList(row, keys), ",") + "\n"
		_, err = of.Write([]byte(strLine))
		levlog.E(err)
	}
}

func main() {
	var cmd = flag.String("cmd", "cmd",
		`Commands of this util
	ea [outputFileName]: export annotation From Data base
	ed [outputFileName]: export all things From Data base
		`)
	var outfile = flag.String("outfile", "", "argument1")
	flag.Parse()

	levlog.Info(*cmd)
	switch *cmd {
	case "cmd":
		flag.Usage()
		levlog.Fatal("No command")
	case "ea":
		levlog.Info("exporting annotation data to ", *outfile)
		if *outfile == "" {
			flag.Usage()
			levlog.Fatal("No output file name")
		}
		ExportAnnotationFromDB(*outfile)
	case "ed":
		levlog.Info("exporting image database to ", *outfile)
		if *outfile == "" {
			flag.Usage()
			levlog.Fatal("No output file name")
		}
		ExportImageDB(*outfile)
	}
}
